"""
认证相关API - 符合用友云开放平台规范
"""
from flask import Blueprint, jsonify, request
from app.services.auth_service import AuthService
from app.utils.response import success_response, error_response
import logging

logger = logging.getLogger(__name__)
auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/iuap-api-auth/open-auth/selfAppAuth/base/v1/getAccessToken', methods=['GET'])
def get_access_token_v1():
    """
    获取access_token - 用友云标准接口（新版）

    参数：
    - appKey: 应用的appKey
    - timestamp: 毫秒级时间戳
    - signature: 签名
    """
    try:
        app_key = request.args.get('appKey')
        timestamp = request.args.get('timestamp')
        signature = request.args.get('signature')

        # 验证必要参数
        if not app_key or not timestamp or not signature:
            return jsonify({
                "code": "40000",
                "message": "缺少必要参数：appKey, timestamp, signature"
            }), 400

        # 转换时间戳为整数
        try:
            timestamp = int(timestamp)
        except ValueError:
            return jsonify({
                "code": "40000",
                "message": "时间戳格式错误，必须是数字"
            }), 400

        logger.info(f"Token请求: appKey={app_key}, timestamp={timestamp}")

        # 调用认证服务获取token
        result = AuthService.get_access_token(app_key, timestamp, signature)

        # 返回结果
        if result.get('code') == '00000':
            logger.info(f"Token生成成功: {result['data']['access_token'][:8]}...")
            return jsonify(result), 200
        else:
            logger.warning(f"Token生成失败: {result.get('message')}")
            return jsonify(result), 401

    except Exception as e:
        logger.error(f"Token获取异常: {str(e)}")
        return jsonify({
            "code": "50000",
            "message": f"服务器内部错误: {str(e)}"
        }), 500


@auth_bp.route('/iuap-api-auth/open-auth/selfAppAuth/getAccessToken', methods=['GET'])
def get_access_token_legacy():
    """
    获取access_token - 用友云标准接口（旧版，兼容）
    """
    return get_access_token_v1()


@auth_bp.route('/yonbip/auth/token', methods=['POST'])
def get_auth_token():
    """
    简化的认证接口（用于测试）
    兼容旧版本，不需要签名
    """
    try:
        data = request.get_json() or {}
        username = data.get('username', 'test_user')
        password = data.get('password', 'test_pass')

        if username and password:
            token_data = AuthService.generate_token(username)
            return success_response("认证成功", token_data)
        else:
            return error_response("用户名或密码错误", code="401"), 401

    except Exception as e:
        logger.error(f"认证异常: {str(e)}")
        return error_response(f"认证失败: {str(e)}"), 500


@auth_bp.route('/yonbip/auth/app/list', methods=['GET'])
def get_app_list():
    """获取应用列表（管理接口）"""
    try:
        apps = AuthService.get_app_list()
        return success_response("查询成功", {"apps": apps})
    except Exception as e:
        logger.error(f"查询应用列表异常: {str(e)}")
        return error_response(f"查询失败: {str(e)}"), 500